<template>
  <div id="app">
    <AppNavbar />

    <div class="job-list-container">
      <div class="header">
        <h1>我的招聘岗位</h1>
        <button class="create-btn" @click="createJob">发布新岗位</button>
      </div>

      <div class="job-list">
        <div
          v-for="job in jobList"
          :key="job.positionId"
          class="job-item"
        >
          <!-- 左侧内容：职位名称和标签 -->
          <div class="job-left-content">
            <div class="job-header">
              <h2 class="job-title">{{ job.positionName }}</h2>
              <span class="position-type">{{ getPositionTypeText(job.positionType) }}</span>
              <!-- 添加状态标签 -->
              <span :class="['status-tag', { 'status-active': job.status === '1', 'status-inactive': job.status === '0' }]">
                {{ getStatusText(job.status) }}
              </span>
            </div>

            <!-- 将省份标签与技能标签放在同一行 -->
            <div class="job-tags-container">
              <div class="job-tags" v-if="job.tagList && job.tagList.length > 0">
                <span
                  v-for="(tag, index) in job.tagList"
                  :key="index"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>

              <!-- 省份标签紧贴在技能标签右边 -->
              <div class="job-location" v-if="job.province">
                <span class="location-tag">{{ job.province }}</span>
              </div>
            </div>
          </div>

          <!-- 右侧操作区域 -->
          <div class="job-right-content">
            <span class="salary-text">{{ job.salaryRange }}</span>
            <div class="job-actions">
              <button
                class="edit-btn"
                @click="editJob(job.positionId)"
              >
                编辑
              </button>

              <div class="manage-dropdown" @click.stop>
                <button
                  class="manage-btn"
                  @click="toggleManageDropdown(job.positionId)"
                >
                  管理 ▼
                  <!-- 未读红点 -->
                  <span
                    v-if="!job.isRead"
                    class="unread-dot"
                  >
                    未读
                  </span>
                </button>

                <div
                  v-show="activeDropdown === job.positionId"
                  class="manage-dropdown-menu"
                  @click.stop
                >
                  <div class="dropdown-item" @click="viewApplications(job.positionId)">
                    查看应聘者
                    <!-- 未读红点 -->
                    <span
                      v-if="!job.isRead"
                      class="dropdown-unread-dot"
                    >
                      未读
                    </span>
                  </div>
                  <div class="dropdown-item" @click="viewStatistics(job.positionId)">
                    查看统计数据
                  </div>
                  <div class="dropdown-item" @click="toggleStatus(job.positionId)">
                    {{ getStatusActionText(job.status) }}
                  </div>
                  <div class="dropdown-item" @click="deleteJob(job.positionId)">
                    删除岗位
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="jobList.length === 0" class="empty-state">
          <p>暂无招聘岗位</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'EmployerJobListView',
  components: {
    AppNavbar
  },
  setup () {
    const jobList = ref([])
    const router = useRouter()
    const activeDropdown = ref(null)
    let websocketMessageHandler = null

    onMounted(() => {
      fetchJobList()
      document.addEventListener('click', closeAllDropdowns)
      setupWebsocketListener()
    })

    onBeforeUnmount(() => {
      document.removeEventListener('click', closeAllDropdowns)
      removeWebsocketListener()
    })

    const closeAllDropdowns = () => {
      activeDropdown.value = null
    }

    const setupWebsocketListener = async () => {
      try {
        const { useWebsocketStore } = await import('@/store/websocket')
        const websocketStore = useWebsocketStore()

        // 定义消息处理函数
        websocketMessageHandler = (data) => {
          // 处理类型为 delivery 的消息
          if (data.isSystem === true && data.type === 'delivery') {
            const positionId = data.fromId
            // 查找对应的职位并设置为未读
            const job = jobList.value.find(item => item.positionId === positionId)
            if (job && job.isRead) {
              job.isRead = false
            }
          }
        }

        // 添加消息监听器
        websocketStore.addMessageListener(websocketMessageHandler)
      } catch (error) {
        console.error('设置WebSocket监听器失败:', error)
      }
    }

    const removeWebsocketListener = async () => {
      if (websocketMessageHandler) {
        try {
          const { useWebsocketStore } = await import('@/store/websocket')
          const websocketStore = useWebsocketStore()
          websocketStore.removeMessageListener(websocketMessageHandler)
        } catch (error) {
          console.error('移除WebSocket监听器失败:', error)
        }
      }
    }

    const toggleManageDropdown = (positionId) => {
      if (activeDropdown.value === positionId) {
        activeDropdown.value = null
      } else {
        activeDropdown.value = positionId
      }
    }

    const fetchJobList = async () => {
      try {
        const response = await apiClient.get('/employer/jobList')

        if (response.data.code === '200') {
          jobList.value = response.data.data.map(job => ({
            ...job,
            isRead: job.isRead !== undefined ? job.isRead : true // 默认为已读
          }))
        } else {
          console.error('获取岗位列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      }
    }

    const getPositionTypeText = (type) => {
      const typeMap = {
        'full-time': '全职',
        'part-time': '兼职',
        internship: '实习'
      }
      return typeMap[type] || type
    }

    const getStatusText = (status) => {
      const statusMap = {
        1: '招聘中',
        0: '已停止'
      }
      return statusMap[status] || '未知状态'
    }

    const getStatusActionText = (status) => {
      return status === '1' ? '暂停招聘' : '重新开启'
    }

    const editJob = (positionId) => {
      // 跳转到岗位修改页面
      router.push(`/job/edit/${positionId}`)
    }

    // 管理功能
    const viewApplications = (positionId) => {
      // 查看应聘者
      router.push(`/job/candidateList/${positionId}`)
      activeDropdown.value = null

      // 标记为已读
      const job = jobList.value.find(item => item.positionId === positionId)
      if (job) {
        job.isRead = true
      }
    }

    const viewStatistics = (positionId) => {
      // 查看统计数据
      router.push(`/job/statistics/${positionId}`)
      activeDropdown.value = null
    }

    const toggleStatus = async (positionId) => {
      // 切换岗位状态
      try {
        const job = jobList.value.find(item => item.positionId === positionId)
        const newStatus = job.status === '1' ? '0' : '1'

        const response = await apiClient.post(`/employer/updateJobStatus/${positionId}`, newStatus, {
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (response.data.code === '200') {
          job.status = newStatus
        } else {
          console.error('更新状态失败:', response.data.msg)
        }
      } catch (error) {
        console.error('更新状态出错:', error)
      }

      activeDropdown.value = null
    }

    const deleteJob = async (positionId) => {
      // 删除岗位
      if (confirm('确定要删除这个岗位吗？')) {
        try {
          const response = await apiClient.delete('/employer/deleteJobPosition', {
            params: {
              positionId: positionId
            }
          })

          if (response.data.code === '200') {
            // 从列表中移除
            jobList.value = jobList.value.filter(item => item.positionId !== positionId)
          } else {
            console.error('删除岗位失败:', response.data.msg)
          }
        } catch (error) {
          console.error('删除岗位出错:', error)
        }
      }

      activeDropdown.value = null
    }

    const createJob = () => {
      // 跳转到创建岗位页面
      router.push('/job/create')
    }

    return {
      jobList,
      activeDropdown,
      getPositionTypeText,
      getStatusText,
      getStatusActionText,
      editJob,
      toggleManageDropdown,
      viewApplications,
      viewStatistics,
      toggleStatus,
      deleteJob,
      createJob
    }
  }
}
</script>

<style scoped>
#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
}
.job-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.header h1 {
  color: #1890ff;
  margin: 0;
}

.create-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.create-btn:hover {
  background-color: #40a9ff;
}

.job-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.job-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s;
}

.job-item:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.job-left-content {
  flex-grow: 1;
  margin-right: 20px;
}

.job-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.job-title {
  margin: 0;
  color: #333;
  font-size: 18px;
  flex-grow: 0;
}

.position-type {
  margin-left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #f9f0ff;
  color: #722ed1;
  white-space: nowrap;
}

/* 调整标签容器为flex布局 */
.job-tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 调整省份标签样式 */
.location-tag {
  background-color: #fffbe6;
  color: #fa8c16;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #ffe58f;
}

.job-right-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.salary-text {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
  white-space: nowrap;
}

.job-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  position: relative;
}

.edit-btn, .manage-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  white-space: nowrap;
  position: relative;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
  border: 1px solid #1890ff;
}

.edit-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.manage-btn {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
  position: relative;
}

.manage-btn:hover {
  background-color: #e6f7ff;
}

/* 未读红点样式 */
.unread-dot {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  line-height: 16px;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  z-index: 2;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  transition: all 0.2s ease;
}

.unread-dot:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.dropdown-unread-dot {
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  line-height: 16px;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  margin-left: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  transition: all 0.2s ease;
}

.dropdown-unread-dot:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.manage-dropdown {
  position: relative;
}

.manage-dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  width: 140px;
  z-index: 1000;
  margin-top: 8px;
  overflow: hidden;
}

.manage-dropdown-menu::before {
  content: '';
  position: absolute;
  top: -6px;
  right: 14px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #ffffff;
}

.dropdown-item {
  padding: 10px 16px;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item:first-child {
  border-radius: 4px 4px 0 0;
}

.dropdown-item:last-child {
  border-radius: 0 0 4px 4px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  color: #999;
}
.status-tag {
  margin-left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

</style>
